var Count = 0;
var gFlagCancel = false;
var bds = []; // 可连接设备列表
var notifyvalue = '';//notify数值
var deviceId = null, bconnect = false;
var bss = [];	// 连接设备服务列表
var serviceId = "49535343-FE7D-4AE5-8FA9-9FAFD205E455";
var bscs = [];	// 连接设备服务对应的特征值列表
var characteristicId = null;//"49535343-1E4D-4BD9-BA61-23C647249616";
var bscws = [];  // 可写特征值列表
var bscns = [];  // notify特征值列表
var wcharacteristicId = "49535343-8841-43F4-A8D4-ECBE34729BB3";
var ncharacteristicId = "49535343-1E4D-4BD9-BA61-23C647249616";

var isreaddata = true; //接收数据完成标志
var szReply = null; // 接收数据数组
var szReplyLen = 0;
var szTemp = null;
var resultCode = 0; // 错误码
var dataField = null;

var nCardType = 0;// 卡类型
var time = 5;//操作超时时间，单位秒。
var nstartUIType = '';
var CardNo = '';

var ConnectBluetoothName = '';
var nOpereationNext = 0;

// 重设数据 
function resetDevices(d){
	d||(bds=[],deviceId=null,document.getElementById('deivce').value='',Count = 0,document.getElementById('CardNo').value='');
}

// 页面初始化操作 
document.addEventListener('plusready', function(e){
	// 监听蓝牙适配器状态变化
	plus.bluetooth.onBluetoothAdapterStateChange(function(e){
		outLine('onBluetoothAdapterStateChange: '+JSON.stringify(e));
	});
	//  监听搜索到新设备 
	plus.bluetooth.onBluetoothDeviceFound(function(e){
		var devices = e.devices;
		outLine('onBluetoothDeviceFound: '+devices.length);
		for(var i in devices){
			outLine(JSON.stringify(devices[i]));
			var device = devices[i];
			const startingStringRegex = /^CW|^J/;
			if(device.deviceId&&device.name&&device.name.length>0&&startingStringRegex.test(device.name)/**/){
				bds.push(device);
			}
		}
		if(!bconnect && bds.length>0){	// 默认选择最后一个
			var n = bds[bds.length-1].name;
			if(!n || n.length<=0){
				n = bds[bds.length-1].deviceId;
			}
			document.getElementById('deivce').value = n;
			ConnectBluetoothName = n;
			deviceId = bds[bds.length-1].deviceId;
		}
	});
	//  监听低功耗蓝牙设备连接状态变化 
	plus.bluetooth.onBLEConnectionStateChange(function(e){
		outLine('onBLEConnectionStateChange: '+JSON.stringify(e));
		if(deviceId == e.deviceId){	// 更新连接状态
			bconnect = e.connected;
			
			if(bconnect)
			{
				startCharacteristicsNotify();				
				document.getElementById('deivce').value="蓝牙已连接:"+ConnectBluetoothName;
			}
			else
			{											
				//disconnectDevice();
				closeBluetooth();
				alert("蓝牙已断开");
			}
		}
	});
	
}, false);

function insertStr(soure, start, newStr){   
   return soure.slice(0, start) + newStr + soure.slice(start);
}

function buffer2StringHexNo0x(value){
	var t='';
	if(value){
		var v=new Uint8Array(value);
		for(var i in v){
			if(v[i]<16)
			{
				t += '0'+v[i].toString(16);
			}
			else 
			t += v[i].toString(16);
		}
	}else{
		t='无效值';
	}
	return t;
}

function buffer2StringHex(value){
	var t='';
	if(value){
		var v=new Uint8Array(value);
		for(var i in v){
			if(v[i]<16)
			{
				t += '0x0'+v[i].toString(16)+' ';
			}
			else
				t += '0x'+v[i].toString(16)+' ';
		}
	}else{
		t='无效值';
	}
	return t;
}

// 打开蓝牙 
function openBluetooth(){
	outSet('打开蓝牙适配器：');
	plus.bluetooth.openBluetoothAdapter({
		success: function(e){
			outLine('打开成功!');
		},
		fail: function(e){
			outLine('打开失败! '+JSON.stringify(e));
		}
	});
}

// 开始搜索蓝牙设备 
function startDiscovery(){
	openBluetooth();
	outSet('开始搜索蓝牙设备：');
	//resetDevices();
	plus.bluetooth.startBluetoothDevicesDiscovery({
		success: function(e){
			outLine('开始搜索成功!');
		},
		fail: function(e){
			outLine('开始搜索失败! '+JSON.stringify(e));
		}
	});
}

// 停止搜索蓝牙设备 
function stopDiscovery(){
	outSet('停止搜索蓝牙设备：');
	plus.bluetooth.stopBluetoothDevicesDiscovery({
		success: function(e){
			outLine('停止搜索成功!');
		},
		fail: function(e){
			outLine('停止搜索失败! '+JSON.stringify(e));
		}
	});
}

// 选择蓝牙设备 
function selectDevice(){
	stopDiscovery();
	if(bds.length <= 0){
		plus.nativeUI.toast('未搜索到有效蓝牙设备!');
		return;
	}
	var bts=[];
	for(var i in bds){
		var t = bds[i].name;
		if(!t || t.length<=0){
			t = bds[i].deviceId;
		}		
		bts.push({title:t});
	}
	plus.nativeUI.actionSheet({title:"选择蓝牙设备",cancel:"取消",buttons:bts}, function(e){
		if(e.index>0){
			document.getElementById('deivce').value = bds[e.index-1].name;
			ConnectBluetoothName = bds[e.index-1].name;
			deviceId = bds[e.index-1].deviceId;
			outLine('选择了"'+bds[e.index-1].name+'"');
		}
	});
}

// 连接蓝牙设备 
function connectDevice(){
	stopDiscovery();
	if(!deviceId){
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	// let timeout = 5000;
	outSet('连接设备: '+deviceId);
	plus.bluetooth.createBLEConnection({
		deviceId: deviceId,
		timeout: 5000,//连接超时时间5000ms
		success: function(e){
			outLine('连接设备成功!'+JSON.stringify(e));
			// startCharacteristicsNotify();
		},
		fail: function(e){
			outLine('连接设备失败! '+JSON.stringify(e));
			alert("连接失败！请点击 <连接蓝牙设备> 按钮重新连接");
		}
	});	
}

// 获取设备服务 
function getServices(){
	if(!deviceId){
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	if(!bconnect){
		plus.nativeUI.toast('未连接蓝牙设备!');
		return;
	}
	resetDevices(true);
	outSet('获取蓝牙设备服务:');
	plus.bluetooth.getBLEDeviceServices({
		deviceId: deviceId,
		success: function(e){
			var services = e.services;
			outLine('获取服务成功! '+services.length);
			if(services.length>0){
				for(var i in services){
					bss.push(services[i]);
					outLine(JSON.stringify(services[i]));
				}
				if(bss.length>0){	// 默认选择最后一个服务
					document.getElementById('service').value = serviceId = bss[bss.length-1].uuid;
				}
			}else{
				outLine('获取服务列表为空?');
			}
		},
		fail: function(e){
			outLine('获取服务失败! '+JSON.stringify(e));
		}
	});
}

// 选择服务 
function selectService(){
	if(bss.length <= 0){
		plus.nativeUI.toast('未获取到有效蓝牙服务!');
		return;
	}
	var bts=[];
	for(var i in bss){
		bts.push({title:bss[i].uuid});
	}
	plus.nativeUI.actionSheet({title:"选择服务",cancel:"取消",buttons:bts}, function(e){
		if(e.index>0){
			document.getElementById('service').value = serviceId = bss[e.index-1].uuid;
			outLine('选择了服务: "'+serviceId+'"');
		}
	});
}

// 获取服务的特征值 
function getCharacteristics(){
	if(!deviceId){
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	if(!bconnect){
		plus.nativeUI.toast('未连接蓝牙设备!');
		return;
	}
	if(!serviceId){
		plus.nativeUI.toast('未选择服务!');
		return;
	}
	resetDevices(true);
	outSet('获取蓝牙设备指定服务的特征值:');
	plus.bluetooth.getBLEDeviceCharacteristics({
		deviceId: deviceId,
		serviceId: serviceId,
		success: function(e){
			var characteristics = e.characteristics;
			outLine('获取特征值成功! '+characteristics.length);
			if(characteristics.length>0){
				for(var i in characteristics){
					var characteristic = characteristics[i];
					outLine(JSON.stringify(characteristic));
					if(characteristic.properties){
						if(characteristic.properties.read){
							bscs.push(characteristics[i]);						
						}
						if(characteristic.properties.write){
							bscws.push(characteristics[i]);
							if(characteristic.properties.notify||characteristic.properties.indicate){
								plus.bluetooth.notifyBLECharacteristicValueChange({	//监听数据变化
									deviceId: deviceId,
									serviceId: serviceId,
									characteristicId: characteristic.uuid,
									success: function(e){
										outLine('notifyBLECharacteristicValueChange '+characteristic.uuid+' success.');
									},
									fail: function(e){
										outLine('notifyBLECharacteristicValueChange '+characteristic.uuid+' failed! '+JSON.stringify(e));
									}
								});
							}
						}
						if(characteristic.properties.notify){
							bscns.push(characteristics[i]);						
						}
					}
				}
				if(bscs.length>0){	// 默认选择最后特征值
					document.getElementById('characteristic').value = characteristicId = bscs[bscs.length-1].uuid;
				}
				if(bscws.length>0){	// 默认选择最后一个可写特征值
					document.getElementById('wcharacteristic').value = wcharacteristicId = bscws[bscws.length-1].uuid;
				}
				if(bscns.length>0){	// 默认选择最后一个可写特征值
					document.getElementById('ncharacteristic').value = ncharacteristicId = bscns[bscns.length-1].uuid;
				}
			}else{
				outLine('获取特征值列表为空?');
			}
		},
		fail: function(e){
			outLine('获取特征值失败! '+JSON.stringify(e));
		}
	});
}

// 选择特征值(读取) 
function selectCharacteristic(){
	if(bscs.length <= 0){
		plus.nativeUI.toast('未获取到有效可读特征值!');
		return;
	}
	var bts=[];
	for(var i in bscs){
		bts.push({title:bscs[i].uuid});
	}
	plus.nativeUI.actionSheet({title:'选择特征值',cancel:'取消',buttons:bts}, function(e){
		if(e.index>0){
			document.getElementById('characteristic').value = characteristicId = bscs[e.index-1].uuid;
			outLine('选择了特征值: "'+characteristicId+'"');
		}
	});
}

// 读取特征值数据 
function readValue(){
	if(!deviceId){
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	if(!bconnect){
		plus.nativeUI.toast('未连接蓝牙设备!');
		return;
	}
	if(!serviceId){
		plus.nativeUI.toast('未选择服务!');
		return;
	}
	if(!characteristicId){
		plus.nativeUI.toast('未选择读取的特征值!');
		return;
	}
	outSet('读取蓝牙设备的特征值数据: ');
	plus.bluetooth.readBLECharacteristicValue({
		deviceId: deviceId,
		serviceId: serviceId,
		characteristicId: characteristicId,
		success: function(e){
			outLine('读取数据成功!'+JSON.stringify(e));
		},
		fail: function(e){
			outLine('读取数据失败! '+JSON.stringify(e));
		}
	});
}

// 选择特征值(写入) 
function selectwCharacteristic(){
	if(bscws.length <= 0){
		plus.nativeUI.toast('未获取到有效可写特征值!');
		return;
	}
	var bts=[];
	for(var i in bscws){
		bts.push({title:bscws[i].uuid});
	}
	plus.nativeUI.actionSheet({title:'选择特征值',cancel:'取消',buttons:bts}, function(e){
		if(e.index>0){
			document.getElementById('wcharacteristic').value = wcharacteristicId = bscws[e.index-1].uuid;
			outLine('选择了特征值: "'+wcharacteristicId+'"');
		}
	});	
}
// 选择特征值(notify) 
function selectnCharacteristic(){
	if(bscns.length <= 0){
		plus.nativeUI.toast('未获取到有效notify特征值!');
		return;
	}
	var bts=[];
	for(var i in bscns){
		bts.push({title:bscns[i].uuid});
	}
	plus.nativeUI.actionSheet({title:'选择特征值',cancel:'取消',buttons:bts}, function(e){
		if(e.index>0){
			document.getElementById('ncharacteristic').value = ncharacteristicId = bscns[e.index-1].uuid;
			outLine('选择了特征值: "'+ncharacteristicId+'"');
		}
	});	
}
// 写入特征值数据 
function writeValue(){
	writeCommand(document.getElementById('writevalue').value);
}

// 启用低功耗蓝牙设备特征值变化时的notify功能
function startCharacteristicsNotify(){
	if(!deviceId){
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	if(!bconnect){
		plus.nativeUI.toast('未连接蓝牙设备!');
		return;
	}
	if(!serviceId){
		plus.nativeUI.toast('未选择服务!');
		return;
	}
	if(!ncharacteristicId){
		plus.nativeUI.toast('未选择notify的特征值!');
		return;
	}
	
	outLine('开始监听notify!');
	
	// 监听低功耗蓝牙设备的特征值变化 
	plus.bluetooth.onBLECharacteristicValueChange(function(e){		
		notifyvalue += buffer2StringHexNo0x(e.value);
		var startSWCode = /^02/;
		var endSWcode = /03$/;
		if(startSWCode.test(notifyvalue)&&endSWcode.test(notifyvalue))
		if(endSWcode.test(notifyvalue))
		{	
			outLine('接收到数据：  '+notifyvalue);//日志显示
			
			var dataFieldLength = notifyvalue.length-4;
			dataField = notifyvalue.substring(10,dataFieldLength);//提取数据域，包含错误码2Byte，序列1Byte
			
			isreaddata = true;
			resultCode = dataField.substr(0,4);//提取错误码，并转换为16进制					
			
			outLine("错误码：                "+resultCode);					
			
			ParsingData(nOpereationNext);
			
			notifyvalue = '';//清空接收数据
		}
						
		if(characteristicId == e.characteristicId){
			// 更新到页面显示
			alert('特征值变化: '+value);
		}
	});
	// 启用notify功能
	plus.bluetooth.notifyBLECharacteristicValueChange({
		deviceId:deviceId,
		serviceId:serviceId,
		characteristicId:ncharacteristicId,
		success:function(e){
			var characteristics = e.characteristics;
			for(var i in characteristics){
				outLine(i+': '+JSON.stringify(characteristics[i]));
			}
		},
		fail:function(e){
			outLine('get characteristics failed: '+JSON.stringify(e));
		}
	});
}

function code2utf8(uni) {
  var uni2 = uni.toString(2);
  if (uni < 128) {file:///D:/通用读卡器通讯协议V2.0-20200306.pdf
    return uni.toString(16);
  } else if (uni < 2048) {
    uni2 = ('00000000000000000' + uni2).slice(-11);
    const s1 =  parseInt("110" + uni2.substring(0, 5), 2);
    const s2 =  parseInt("10" + uni2.substring(5), 2);
    return s1.toString(16) + ',' + s2.toString(16)
  } else {
    uni2 = ('00000000000000000' + uni2).slice(-16);
    const s1 = parseInt('1110' + uni2.substring(0, 4),2 );
    const s2 = parseInt('10' + uni2.substring(4, 10), 2 );
    const s3 = parseInt('10' + uni2.substring(10), 2);
    return s1.toString(16) + ',' + s2.toString(16) + ',' + s3.toString(16)
  }
}

function string2buffer(str) {
  var val = "";
  for (var i = 0; i < str.length; i++) {
    val += ',' + code2utf8(str.charCodeAt(i))
  }
  val += ',00';
  outLine(val);
  // 将16进制转化为ArrayBuffer
  return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h, 16)
  })).buffer
}

//字符串转字符串ArrayBuffer
function str2ab(s,f) {
	var b = new Blob([s],{type:'text/plain'});
	var r = new FileReader();
	r.readAsArrayBuffer(b);
	r.onload = function (){if(f)f.call(null,r.result)}
}
//ArrayBuffer转字符串
function ab2str(u,f) {
   var b = new Blob([u]);
   var r = new FileReader();
	r.readAsText(b, 'utf-8');
	r.onload = function (){if(f)f.call(null,r.result)}
}

// 字符串转16进制
function strToHexCharCode(str) {
　　if(str === "")
　　　　return "";
　　var hexCharCode = [];
　　//hexCharCode.push("0x"); 
　　for(var i = 0; i < str.length; i++) {
　　　　hexCharCode.push("0x"+(str.charCodeAt(i)).toString(16)+' ');
　　}
　　return hexCharCode.join("");
}

// 16进制转字符串
function hexCharCodeToStr(hexCharCodeStr) {
	var rawStr =JudgeStr(hexCharCodeStr);
	
　　	var curCharCode;
　　	var resultStr = [];
　　	for(var i = 0; i < rawStr.length;i = i + 2) {
		if (rawStr.substr(i, 2) == '00') {
			resultStr.push('');
		} else {
			curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
				resultStr.push(String.fromCharCode(curCharCode));//向数组的末尾添加一个或更多元素，并返回新的长度。	
		}
　　	}
　　	return resultStr.join("");//把数组的所有元素放入一个字符串。
}

function prePro(data)
{
	if (data.length % 2) return '';
	var tmp='';
	for(i=0;i<data.length;i+=4)
	{
		tmp += '\\u' + data.charAt(i+2) + data.charAt(i+3)+ data.charAt(i) + data.charAt(i+1);
	}
	return tmp;
}

function hexCharCodeToChinese(hexCharCodeStr){	
   var str = ""; 
   // outLine("prePro"+prePro(hexCharCodeStr));
   var s = prePro(hexCharCodeStr).split('\\u'); 
   for(var i = 0;i < s.length;i++){ 
	   str += String.fromCharCode(parseInt(s[i],16)); 
   } 
   return str; 	
}

// 断开蓝牙设备
function disconnectDevice(){
	if(!deviceId){
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	resetDevices(true);
	outSet('断开蓝牙设备连接：');
	plus.bluetooth.closeBLEConnection({
		deviceId: deviceId,
		success: function(e){
			outLine('断开连接成功!');
		},
		fail: function(e){
			outLine('断开连接失败! '+JSON.stringify(e));
		}
	});
}

// 关闭蓝牙
function closeBluetooth(){
	outSet('关闭蓝牙适配器：');
	resetDevices();
	plus.bluetooth.closeBluetoothAdapter({
		success: function(e){
			outLine('关闭成功!');
			bconnect = false;
		},
		fail: function(e){
			outLine('关闭失败! '+JSON.stringify(e));
		}
	});
}

//下发指令
function writeCommand(cmd){
	if(!deviceId){
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	if(!bconnect){
		plus.nativeUI.toast('未连接蓝牙设备!');
		return;
	}
	if(!serviceId){
		plus.nativeUI.toast('未选择服务!');
		return;
	}
	if(!wcharacteristicId){
		plus.nativeUI.toast('未选择写入的特征值!');
		return;
	}
	
	var value = cmd;//document.getElementById('writevalue').value;
	if(!value || value==''){
		plus.nativeUI.toast('请输入需要写入的数据');
		document.getElementById('writevalue').focus();
		return;
	}
	
	// 要写入的数据
	var rawStr =JudgeStr(value);

	var buffer = new ArrayBuffer(rawStr.length/2);	
	var iv = new Uint8Array(buffer);
　　	for(var i = 0; i < rawStr.length;i += 2) {
		iv[i/2] = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value	
		// outSet('iv['+i/2+'] = '+iv[i/2]);
　　	}

	plus.bluetooth.writeBLECharacteristicValue({
		deviceId: deviceId,//必选 蓝牙设备的id
		serviceId: serviceId,//必选 蓝牙服务的uuid
		characteristicId: wcharacteristicId,//必选 蓝牙特征值的uuid
		value: buffer,// 必选 要写入的数据 写入到蓝牙设备指定特征值中的二进制值。
		success: function(e){ //可选 读取特征值的二进制数据成功回调函数
			outLine('欢迎沟通交流：sunsj@cashwaytech.com');
			outLine('写入数据成功  '+buffer2StringHexNo0x(buffer));
		},
		fail: function(e){ //可选 读取特征值的二进制数据失败回调函数
			outLine('写入数据失败  '+JSON.stringify(e));
		}
	});	
}

//判断字符串是否是0x开头，且长度是2的整数倍；返回截取0x以后字符串。
function JudgeStr(str){
	var trimedStr = str.trim();
	var rawStr = trimedStr.substr(0,2).toLowerCase() === "0x" ? trimedStr.substr(2) //抽取2字节的子串
	　　	: 
	　　	trimedStr;	
	
	var len = rawStr.length;
	if(len % 2 !== 0) {
	　　alert("Illegal Format ASCII Code!");
	　　return "";
	}	
	
	return rawStr;
}


// assemble_cmd("0F10"+'0210');
// assemble_cmd("Command"+"Parameter");跳过命令序列号
function assemble_cmd(cmd) {
	
	// 要写入的数据
	var assembleStr='';
	var rawStr=JudgeStr(cmd);
	
	var buffer = new ArrayBuffer(rawStr.length/2 + 8);	
	var iv = new Uint8Array(buffer);
	var ivlen = 0;	
	iv[ivlen++] = 0x02;
	iv[ivlen++] = 0x00;
	iv[ivlen++] = 0x00;
	iv[ivlen++] = 0x00;
	iv[ivlen++] = rawStr.length/2+1;
	for(var i = 0; i < 4;i += 2) {
		iv[ivlen++] = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value	
	}

	if(Count++ >256)
		Count = 0;
	iv[ivlen++] = Count;
	
	for(var i = 4; i < rawStr.length;i += 2) {
		iv[ivlen++] = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value	
		//outSet('iv[ivlen+'+i/2+'] = '+iv[i/2]);
	}		
		
	var temp;
	// 异或运算值 CheckSum
	for(var i=0;i<=ivlen;i++)
	{
	    temp ^= iv[i];
	}	
	iv[ivlen++] = temp;
	
	//End
	iv[ivlen++]=0x03;
	
	//设置超时时间
	if((iv[5]==0x07 && iv[6]==0x00)
	   ||(iv[5]==0x07 && iv[6]==0x01)
	   ||(iv[5]==0x07 && iv[6]==0x03)
	   ||(iv[5]==0x36 && iv[6]==0x00)
	   ||(iv[5]==0x35 && iv[6]==0x00)
	   ||(iv[5]==0x35 && iv[6]==0x01)
	   ||(iv[5]==0x40 && iv[6]==0x10)
	   ||(iv[5]==0x40 && iv[6]==0x20))
	{	    
	    iv[8] = time;
	}
	if(iv[5]==0x31 && iv[6]==0xfa)
	{
		iv[9] = time+1;
	}
	
	return buffer2StringHexNo0x(iv);	
}

//command：控制指令
//Parameter：控制参数
//跳过命令序列号
function SendAPDU(command,Parameter) {
	try{	
		var strCmd = assemble_cmd(command+Parameter);
		writeCommand(strCmd);		
			
	}catch(err)
	{
		outLine("发送APDU失败"+err);
	}								   
}		

//UI类型（0x01=idc，0x02=rf，0x03=icc，0x04=fng，0x05=msr，0x06=EPP，0x06=icc）
function user_startUI(type)
{	
	nstartUIType = JudgeStr(type);
	SendAPDU("31EF","00");//"31EFxx00" 暂停电池电量显示	
	nOpereationNext = 9;					
}

function user_endUI(type)
{			
	var nType = JudgeStr(type);
	SendAPDU("31FE",nType);// 暂停Android主板读取IC板串口
	nOpereationNext = 0;
}

function readidc() {	
	// confirm("请先放好身份证，然后点击确认。");
	document.getElementById('CardNo').value="读取身份证...";
	user_startUI('0x01');	
}

function HandleIdc() {	
	if(resultCode == '0422')
	{
		document.getElementById('CardNo').value="读身份证失败";
		outLine("读身份证失败");
		alert("读身份证失败");
	}else if(resultCode == '0000')
	{
		var idName = hexCharCodeToChinese(dataField.substr(24, 60));//姓名	
		var idSex = hexCharCodeToStr(dataField.substr(84, 4));//性别
		var idNation= hexCharCodeToStr(dataField.substr(88, 8));//民族
		var idBirthday = hexCharCodeToStr(dataField.substr(96, 32));//出生日期
		var idAddress = hexCharCodeToChinese(dataField.substr(128, 140));//住址
		var idNum = hexCharCodeToStr(dataField.substr(268, 72));//身份证号码
		var idIssAuth = hexCharCodeToChinese(dataField.substr(340, 60));//签发机关
		var idActiveStart = hexCharCodeToStr(dataField.substr(400, 32));//有效期起始
		var idActiveEnd = hexCharCodeToStr(dataField.substr(432, 32));//有效期截止
		var idLastAddress = hexCharCodeToChinese(dataField.substr(464, 140));//最新住址
		var idPicture = hexCharCodeToStr(dataField.substr(604));//身份证图片

		document.getElementById('CardNo').value='读取身份证成功！';
		outLine("姓名：\t" + idName+'\n'+
				"出生日期：\t" + idBirthday+'\n'+
				"住址：\t" + idAddress+'\n'+
			    "身份证号：\t" + idNum+'\n'+
				"签发机关：\t" + idIssAuth+'\n'+
			    "有效期：\t" + idActiveStart+'到'+idActiveEnd+'\n');		
		alert("姓名：\t" + idName+'\n'+
				"出生日期：\t" + idBirthday+'\n'+
				"住址：\t" + idAddress+'\n'+
			    "身份证号：\t" + idNum+'\n'+
				"签发机关：\t" + idIssAuth+'\n'+
			    "有效期：\t" + idActiveStart+'到'+idActiveEnd+'\n');
	}			
}

function readrfc() {	
	document.getElementById('CardNo').value="读取非接触卡...";
	user_startUI('0x02');	
}


function readfng() {	
	user_startUI('0x04');	
}

function readmsr() {	
	user_startUI('0x05');
}

function readEPP() {	
	user_startUI('0x06');
}


function readver(){
	// // outLine("readver in");
	// var strCmd = assemble_cmd("0F10"+'');
	// // outLine('组装后的指令：'+strCmd);
	// writeCommand(strCmd);
	// // writeCommand("02000000030420113403");
	// // 02000000130000110f594b323630392d494f53302d5634322503
	// // YK2609-IOS0-V42	
	// // outLine("readver out");
	// // outLine("sunsj@cashwaytech.com);
	// outLine("整理后的数据："+JudgeStr(document.getElementById('writevalue').value));	
			
	nOpereationNext = 7;
	SendAPDU("0F10",'');	
}


function funselect(FunSelect){	

	//选择类型（0x01=idc，0x02=rfc，0x03=icc，0x04=fng，0x05=msr，0x06=EPP，0x06=icc，0x07=ver）
	switch(FunSelect){
		case "idc":
			readidc();
		break;
		case "rfc":
			readrfc();
		break;		
		case "icc":
			readicc();
		break;
		case "fng":
			readfng();
		break;
		case "msr":
			readmsr();
		break;
		case "EPP":
			readEPP();
		break;	
		case "ver":
			readver();
		break;
		default:		
			outLine("non selsect");					
	}	
	
}


function readicc() {
	document.getElementById('CardNo').value="读取接触IC...";
	user_startUI('0x03');	
}

function checkCard() {
	nOpereationNext = 1;
	SendAPDU("0703", '');// check card,all card!
}

function icCardPowerDown() {
	SendAPDU("0303", '00');// Ic card Power Off!
}

function HandleCardType() {
	
	if(nCardType == 0) {
		nOpereationNext = 2;//卡片冷复位
		SendAPDU("0301",'000000');//接触 CPU 卡片状态检测		
	}
	else if (nCardType == 1) {
		nOpereationNext = 2;//调试非接触卡的顺序
		SendAPDU("0410",'');//射频 CPU 卡复位
	}
}

function setCardType() {
	// nOpereationNext = 3;
	if (nCardType == 0) {
		SendAPDU("4B09", '0000'); //设置IC卡类型
	} else if (nCardType == 1) {
		SendAPDU("4B09", '0100'); //设置IC卡类型
	}
}

function getCardInfo() {
	// nOpereationNext = 4;
	SendAPDU("4B60", '0006210109215700');
}

function getCardNum() {// 
	// nOpereationNext = 6;
	SendAPDU("4B40", '00015A');
}

function SelectReadStart(FunSelect){//选择界面后续处理	

	//选择类型（0x01=idc，0x02=rfc，0x03=icc，0x04=fng，0x05=msr，0x06=EPP，0x06=icc）
	switch(FunSelect){
		case '01':{
			nOpereationNext = 5;
			SendAPDU("0420",'');	
		break;
		}
		case '02':{
			checkCard();
		break;
		}		
		case '03':{
			checkCard();
		break;
		}
		case '04':{
			// readfng();
		break;
		}
		case '05':{
			// readmsr();
		break;
		}
		case '06':{
			// readEPP();
		break;	
		}
		default:		
			outLine("non selsect");					
	}	
}

function ParsingData(select) {
	
	switch(select){
		case 1: {// 检卡操作
			if (resultCode == "0701" ) {
				nOpereationNext = 0;
				// outLine("等待刷磁条卡超时!");
				// alert("等待刷磁条卡超时!");
				if(nCardType == 0){
					document.getElementById('CardNo').value="请正确插入卡片，重新点击读取!";
					outLine("请正确插入卡片，重新点击读取!");
					alert("请正确插入卡片，重新点击读取!");
				}
				if(nCardType == 1){
					document.getElementById('CardNo').value="请把卡片放入读卡区，重新点击读取!";
					outLine("请把卡片放入读卡区，重新点击读取!");
					alert("请把卡片放入读卡区，重新点击读取!");
				}
			} else if (resultCode == "0702") {
				nOpereationNext = 0;
				document.getElementById('CardNo').value="无效磁条卡!";
				outLine("无效磁条卡!");
				alert("无效磁条卡!");
			} else if (resultCode == "0710") {
				document.getElementById('CardNo').value="检测有接触卡片";
				outLine("检测有接触卡片");
				nCardType = 0;
				HandleCardType();
			} else if (resultCode == "0711" ) {
				document.getElementById('CardNo').value="检测有非接触卡片";
				outLine("检测有非接触卡片");
				nCardType = 1;
				HandleCardType();
			}  else if (resultCode == "0011") {
				nOpereationNext = 0;
				document.getElementById('CardNo').value="参数长度错误!";
				outLine("参数长度错误!");
				alert("参数长度错误!");
			} else if (resultCode == "0712" ) {
				nOpereationNext = 0;
				document.getElementById('CardNo').value="检测有居民身份证!";
				outLine("检测有居民身份证!");
				alert("检测有居民身份证!");
			} 
			else {
				checkCard();
				nOpereationNext = 0;
			}
			
			break;
		} 
		case 2: {
			// 设置卡片类型
			setCardType();
			nOpereationNext = 3;
			break;
		} 
		case 3: {
			// 读取卡信息
			getCardInfo();
			nOpereationNext = 4;
			break;
		} 
		case 4: {
			// 获取卡号
			getCardNum();
			nOpereationNext = 6;
			break;
		} 
		case 5: {
			// 处理身份证	
			HandleIdc();
			user_endUI('0x01');			
			nOpereationNext = 0;
			break;
		} 
		case 6: {// 处理结果  000c5a0a6235820099021574823f
			if(resultCode == '0000') {
				CardNo = dataField.substr(14, 16);
			}
			
			icCardPowerDown();
			nOpereationNext = 8;
			break;
		}
		case 7: {
			var Ver = hexCharCodeToStr(dataField.substr(8));
			document.getElementById('CardNo').value="读取到固件版本 "+Ver;	
			alert("读取到固件版本 "+Ver);
			outLine("读取到固件版本 "+Ver);
			plus.device.beep(5);//蜂鸣5次
			nOpereationNext = 0;
			break;
		}
		case 8:{		
			document.getElementById('CardNo').value="卡号 ：" + CardNo;
			alert("卡号 ：" + CardNo);
			outLine("卡号 ：" + CardNo);
			if(nCardType == 0)
				user_endUI('0x03');	
			if(nCardType == 1)
				user_endUI('0x02');	
			nOpereationNext = 0;
			break;
		}
		case 9:{//user_endUI('00')
			SendAPDU("31FA",nstartUIType+'05'+"00");// 05:UI显示超时时间,拼接显示ui指令
			nOpereationNext = 10;
			break;
		}
		case 10:{//user_startUI
			SelectReadStart(nstartUIType);//选择读卡流程入口			
			break;			
		}
		default:{
			nOpereationNext = 0;
		}
	 }
	 
	if(nOpereationNext) 
		outLine("NextOpereationCode:"+nOpereationNext);	 		
}

